// 文件路径: src/main/java/com/macro/mall/tiny/modules/oms/service/impl/CartServiceImpl.java
package com.macro.mall.tiny.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macro.mall.tiny.modules.oms.dto.CartChangeSkuParam;
import com.macro.mall.tiny.modules.oms.dto.CartListQueryParam;
import com.macro.mall.tiny.modules.oms.dto.CartParam;
import com.macro.mall.tiny.modules.oms.dto.CartUpdateParam;
import com.macro.mall.tiny.modules.oms.mapper.CartMapper;
import com.macro.mall.tiny.modules.oms.model.Cart;
import com.macro.mall.tiny.modules.oms.service.CartService;
import com.macro.mall.tiny.modules.oms.vo.CartItemVO;
import com.macro.mall.tiny.modules.pms.model.ProductSku;
import com.macro.mall.tiny.modules.pms.service.ProductSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author macro
 * @since 2023-11-07
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    // 在类中添加依赖
    @Autowired
    private ProductSkuService productSkuService;
    
    @Autowired
    private com.macro.mall.tiny.security.util.JwtTokenUtil jwtTokenUtil;

    @Override
    public List<Cart> list(Integer userId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
                .eq(Cart::getDelFlag, 0)
                .orderByDesc(Cart::getCreatedAt);
        return list(wrapper);
    }

    // 在 CartServiceImpl 类中添加以下方法
    @Override
    public Page<CartItemVO> pageListWithProductInfo(CartListQueryParam queryParam) {
        // 设置默认分页参数
        if (queryParam.getPageNum() == null) {
            queryParam.setPageNum(1);
        }
        if (queryParam.getPageSize() == null) {
            queryParam.setPageSize(10);
        }

        // 构建分页对象
        Page<Cart> cartPage = new Page<>(queryParam.getPageNum(), queryParam.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();

        // 用户ID筛选
        if (queryParam.getUserId() != null) {
            wrapper.eq(Cart::getUserId, queryParam.getUserId());
        }

        // SKU ID筛选
        if (queryParam.getSkuId() != null) {
            wrapper.eq(Cart::getSkuId, queryParam.getSkuId());
        }

        // 加购时间范围筛选
        if (queryParam.getCreateTimeStart() != null) {
            wrapper.ge(Cart::getCreatedAt, queryParam.getCreateTimeStart());
        }

        if (queryParam.getCreateTimeEnd() != null) {
            wrapper.le(Cart::getCreatedAt, queryParam.getCreateTimeEnd());
        }

        // 只查询未删除的记录
        wrapper.eq(Cart::getDelFlag, 0)
                .orderByDesc(Cart::getCreatedAt);

        // 分页查询购物车列表
        Page<Cart> cartResultPage = page(cartPage, wrapper);

        // 获取购物车列表
        List<Cart> cartList = cartResultPage.getRecords();

        // 批量查询商品信息
        List<CartItemVO> result = new ArrayList<>();
        if (!cartList.isEmpty()) {
            // 提取所有skuId
            List<Integer> skuIds = cartList.stream()
                    .map(Cart::getSkuId)
                    .distinct()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            // 批量查询商品信息
            List<ProductSku> productSkus = new ArrayList<>();
            if (!skuIds.isEmpty()) {
                productSkus = productSkuService.listByIds(skuIds);
            }

            Map<Integer, ProductSku> skuMap = productSkus.stream()
                    .collect(Collectors.toMap(ProductSku::getSkuId, Function.identity()));

            // 组装返回结果
            for (Cart cart : cartList) {
                CartItemVO itemVO = new CartItemVO();
                itemVO.setCart(cart);
                itemVO.setProductSku(skuMap.get(cart.getSkuId()));
                result.add(itemVO);
            }
        }

        // 构建返回的分页对象
        Page<CartItemVO> resultPage = new Page<>(cartResultPage.getCurrent(), cartResultPage.getSize(), cartResultPage.getTotal());
        resultPage.setRecords(result);

        return resultPage;
    }


    @Override
    @Transactional
    public Integer addToCart(CartParam cartParam) {
        // 如果userId为null或0，尝试从token中解析
        if ((cartParam.getUserId() == null || cartParam.getUserId() == 0) && cartParam.getToken() != null) {
            try {
                String userIdStr = jwtTokenUtil.getUserNameFromToken(cartParam.getToken());
                if (userIdStr != null && !userIdStr.isEmpty()) {
                    cartParam.setUserId(Integer.parseInt(userIdStr));
                }
            } catch (Exception e) {
                throw new RuntimeException("无效的token");
            }
        }

        // 检查userId是否有效
        if (cartParam.getUserId() == null || cartParam.getUserId() == 0) {
            throw new RuntimeException("用户ID不能为空");
        }

        CartMapper cartMapper = (CartMapper) baseMapper;
        // 检查购物车中是否已存在该商品
        boolean exists = cartMapper.existsByUserIdAndSkuId(cartParam.getUserId(), cartParam.getSkuId());

        if (exists) {
            // 如果已存在，则更新数量和备注
            Cart existingCart = cartMapper.getByUserIdAndSkuId(cartParam.getUserId(), cartParam.getSkuId());
            existingCart.setQty(existingCart.getQty() + cartParam.getQty());
            if (cartParam.getRemark() != null) {
                existingCart.setRemark(cartParam.getRemark());
            }
            existingCart.setUpdatedAt(LocalDateTime.now());
            updateById(existingCart);
            return existingCart.getCartId(); // Return existing cart ID
        } else {
            // 如果不存在，则新增
            Cart cart = new Cart();
            BeanUtils.copyProperties(cartParam, cart);
            cart.setDelFlag(0);
            cart.setCreatedAt(LocalDateTime.now());
            cart.setUpdatedAt(LocalDateTime.now());
            cart.setUserId(cartParam.getUserId());
            save(cart);
            return cart.getCartId(); // Return new cart ID
        }
    }

    @Override
    public boolean updateCart(Integer cartId, CartUpdateParam updateParam) {
        // 获取原始购物车项以保留userId
        Cart originalCart = getById(cartId);
        if (originalCart == null) {
            return false;
        }

        Cart cart = new Cart();
        cart.setCartId(cartId);
        
        // 保留原始userId，确保不被更新为null
        cart.setUserId(originalCart.getUserId());
        
        if (updateParam.getQty() != null) {
            cart.setQty(updateParam.getQty());
        }
        if (updateParam.getRemark() != null) {
            cart.setRemark(updateParam.getRemark());
        }
        cart.setUpdatedAt(LocalDateTime.now());
        return updateById(cart);
    }

    @Override
    public boolean deleteFromCart(Integer cartId) {
        Cart cart = new Cart();
        cart.setCartId(cartId);
        cart.setDelFlag(1);
        cart.setUpdatedAt(LocalDateTime.now());
        return updateById(cart);
    }

    @Override
    @Transactional
    public boolean changeSku(CartChangeSkuParam changeSkuParam) {
        Integer cartId = changeSkuParam.getCartId();
        Integer newSkuId = changeSkuParam.getNewSkuId();

        // 获取原购物车项
        Cart originalCart = getById(cartId);
        if (originalCart == null || originalCart.getDelFlag() == 1) {
            return false;
        }

        CartMapper cartMapper = (CartMapper) baseMapper;
        boolean exists = cartMapper.existsByUserIdAndSkuId(originalCart.getUserId(), newSkuId);

        if (exists) {
            // 如果新SKU已在购物车中，则合并数量
            Cart existingCart = cartMapper.getByUserIdAndSkuId(originalCart.getUserId(), newSkuId);
            Integer newQty = changeSkuParam.getQty() != null ?
                    changeSkuParam.getQty() : originalCart.getQty();
            existingCart.setQty(existingCart.getQty() + newQty);
            existingCart.setUpdatedAt(LocalDateTime.now());
            updateById(existingCart);

            // 删除原购物车项
            originalCart.setDelFlag(1);
            originalCart.setUpdatedAt(LocalDateTime.now());
            updateById(originalCart);
        } else {
            // 如果新SKU不在购物车中，则直接更新SKU
            originalCart.setSkuId(newSkuId);
            if (changeSkuParam.getQty() != null) {
                originalCart.setQty(changeSkuParam.getQty());
            }
            originalCart.setUpdatedAt(LocalDateTime.now());
            updateById(originalCart);
        }

        return true;
    }

    @Override
    public boolean deleteBatch(List<Integer> cartIds) {
        if (CollectionUtils.isEmpty(cartIds)) {
            return false;
        }

        List<Cart> cartList = listByIds(cartIds);
        for (Cart cart : cartList) {
            cart.setDelFlag(1);
            cart.setUpdatedAt(LocalDateTime.now());
        }
        return updateBatchById(cartList);
    }
    
    @Override
    public boolean deleteByUserIdAndSkuIds(Integer userId, List<Integer> skuIds) {
        if (userId == null || CollectionUtils.isEmpty(skuIds)) {
            return false;
        }
        
        // 构建查询条件
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getUserId, userId)
                .in(Cart::getSkuId, skuIds)
                .eq(Cart::getDelFlag, 0);
        
        // 查询需要删除的购物车项
        List<Cart> cartList = list(queryWrapper);
        
        if (CollectionUtils.isEmpty(cartList)) {
            return false;
        }
        
        // 更新delFlag为1
        for (Cart cart : cartList) {
            cart.setDelFlag(1);
            cart.setUpdatedAt(LocalDateTime.now());
        }
        
        return updateBatchById(cartList);
    }
}